package com.oocl.aeat.jms;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

import com.oocl.aeat.util.ServerConfig;

/**
 * 消息生产者
 * @author Administrator
 *
 */
public class JMSProducer {
	
	private static Connection connection;
	/**
	 * 构造方法私有化
	 */
	private JMSProducer(){}
	
	public static void init() {
		// 连接工厂
		ConnectionFactory connectionFactory; 
		try {
			connectionFactory=new ActiveMQConnectionFactory(ServerConfig.JMS_USERNAME,ServerConfig.JMS_PASSWORD,ServerConfig.JMS_TCP_CONNNECTION_URL);
			// 通过连接工厂获取连接
			connection=connectionFactory.createConnection();
			// 启动连接
			connection.start(); 
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	public static void destroy() {
		if(connection!=null){
			try {
				connection.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	public static void send(String queueName, String text) {
		try {
			// 创建Session
			Session session=connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			// 根据 queueName , 创建 消息的目的地
			Destination destination=session.createQueue(queueName); 
			// 创建消息生产者
			MessageProducer messageProducer=session.createProducer(destination); 
			// 创建 发送的消息体
			TextMessage message=session.createTextMessage( text );
			// 发送消息
			messageProducer.send(message);
			
			session.commit();
			session.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
}
